//
//  ZLComposetextView.swift
//  ZLWeibo
//
//  Created by zhanglongtao on 17/1/12.
//  Copyright © 2017年 hanju001. All rights reserved.
//

import UIKit

//撰写微博的文本视图
class ZLComposetextView: UITextView {

    fileprivate lazy var placeholderLabel = UILabel()
    
    override func awakeFromNib() {
        
        setUpUI()
    }
  
    @objc fileprivate func textChange() {
        
        
        placeholderLabel.isHidden = self.hasText
    }
    deinit {
        
        NotificationCenter.default.removeObserver(self)
    }

}
// MARK --- 表情键盘专属方法
extension ZLComposetextView {
    
    func insertEmotion(em: ZLEmotion?) {
        
        guard let em = em else{
            
            //删除文本
            deleteBackward()
            
            return
        }
        // emoji 字符串
        if let emoji = em.emoji, let textRange = selectedTextRange {
            
            replace(textRange, withText: emoji)
            
            return
        }
        //所有的排版系统中几乎都有共同的一个特点，插入的字符的显示，跟随前一个属性,但是本身没有属性
        //图片表情
        let imageText = NSMutableAttributedString(attributedString: em.imageText(font: font!))
        
        imageText.addAttributes([NSFontAttributeName: font!], range: NSRange(location: 0, length: 1))
        
        let attrStrM = NSMutableAttributedString(attributedString: attributedText)
        
        attrStrM.replaceCharacters(in: selectedRange, with: imageText)
        //记录光标位置
        let range = selectedRange
        
        //设置文本
        attributedText = attrStrM
        //恢复光标位置
        selectedRange = NSRange(location: range.location + 1, length: 0)
        //让代理执行文本变化方法
        delegate?.textViewDidChange?(self)
        //执行当前文本变化方法
        textChange()
        
    }
    //返回textView对应的纯文本本字符串（将图片属性转换为文字）
    var emotionText: String {
        
        //获取TextView的属性文本
        guard let attStr = attributedText else {
            
            return ""
        }
        
        var result = String()
        attStr.enumerateAttributes(in: NSRange(location: 0, length: attStr.length), options: [], using: { (dict, range, _) in
            
            
            if let attachment = dict["NSAttachment"] as? ZLEmotionAttachment {
                
                result += attachment.chs ?? ""
            }else{
                
                let subStr = (attStr.string as NSString).substring(with: range)
                
                result += subStr
            }
            
        })
        
        return result
    }
}
private extension ZLComposetextView {
    
    func setUpUI() {
        
        NotificationCenter.default.addObserver(self, selector: #selector(textChange), name: NSNotification.Name.UITextViewTextDidChange, object: nil)
        
        placeholderLabel.text = "分享新鲜事..."
        placeholderLabel.font = self.font
        placeholderLabel.textColor = UIColor.lightGray
        placeholderLabel.frame.origin = CGPoint(x: 5, y: 8)
        placeholderLabel.sizeToFit()
        
        addSubview(placeholderLabel)
        
    }
}
